{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "7479fb56",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Collecting pypdf\n",
      "  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/07/f3/4939b609cfd374e495450b22a0385ee3f531e9aa40e8812e5c405f030c54/pypdf-6.1.0-py3-none-any.whl (322 kB)\n",
      "Requirement already satisfied: typing_extensions>=4.0 in c:\\users\\a\\.conda\\envs\\langchainv1\\lib\\site-packages (from pypdf) (4.15.0)\n",
      "Installing collected packages: pypdf\n",
      "Successfully installed pypdf-6.1.0\n"
     ]
    }
   ],
   "source": [
    "! pip install pypdf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3d9e208f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import init_chat_model\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "llm = init_chat_model(\n",
    "    \"deepseek:deepseek-chat\",\n",
    "    temperature=0\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "86e9a276",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\a\\.conda\\envs\\langchainV1\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "\n",
    "embeddings = HuggingFaceEmbeddings(model_name=r\"D:\\modelscope\\cache\\bge-m3\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c95591c9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.vectorstores import InMemoryVectorStore\n",
    "\n",
    "vector_store = InMemoryVectorStore(embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a0d629d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Blog Post Agent\n",
    "\n",
    "import bs4\n",
    "from langchain.agents import AgentState, create_agent\n",
    "from langchain_community.document_loaders import PyPDFLoader\n",
    "from langchain_core.messages import MessageLikeRepresentation\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "from langchain_core.tools import tool\n",
    "\n",
    "# Load and chunk contents of the blog\n",
    "loader = PyPDFLoader(r\"..\\langchain官网学习-v1版本\\data\\国华人寿保险股份有限国华附加互联网真爱全民保养老年金保险产品说明书.pdf\")\n",
    "docs = loader.load()\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)\n",
    "all_splits = text_splitter.split_documents(docs)\n",
    "\n",
    "# Index chunks\n",
    "_ = vector_store.add_documents(documents=all_splits)\n",
    "\n",
    "# Construct a tool for retrieving context\n",
    "@tool(response_format=\"content_and_artifact\")\n",
    "def retrieve_context(query: str):\n",
    "    \"\"\"Retrieve information to help answer a query.\"\"\"\n",
    "    retrieved_docs = vector_store.similarity_search(query, k=2)\n",
    "    serialized = \"\\n\\n\".join(\n",
    "        (f\"Source: {doc.metadata}\\nContent: {doc.page_content}\")\n",
    "        for doc in retrieved_docs\n",
    "    )\n",
    "    return serialized, retrieved_docs\n",
    "\n",
    "tools = [retrieve_context]\n",
    "# If desired, specify custom instructions\n",
    "prompt = (\n",
    "    \"You have access to a tool that retrieves context. \"\n",
    "    \"Use the tool to help answer user queries.\"\n",
    ")\n",
    "agent = create_agent(llm, tools, prompt=prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e349ce4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "用户享有什么权益?\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "我来帮您查询用户权益相关的信息。让我从博客文章中检索相关内容。\n",
      "Tool Calls:\n",
      "  retrieve_context (call_00_2zLyZIwhdIsbh1PJpHkIbuNG)\n",
      " Call ID: call_00_2zLyZIwhdIsbh1PJpHkIbuNG\n",
      "  Args:\n",
      "    query: 用户权益 用户权利 消费者权益\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: retrieve_context\n",
      "\n",
      "Source: {'producer': 'Microsoft: Print To PDF', 'creator': 'PyPDF', 'creationdate': '2023-06-13T18:29:45+08:00', 'author': 'yemy', 'moddate': '2023-06-13T18:29:45+08:00', 'title': 'Microsoft Word - 13-2.ýND€™TQ˜1h\\x11Ý{\\x01tÑÝi§Áô\\x0ef.doc', 'source': '..\\\\langchain官网学习-v1版本\\\\data\\\\国华人寿保险股份有限国华附加互联网真爱全民保养老年金保险产品说明书.pdf', 'total_pages': 5, 'page': 2, 'page_label': '3'}\n",
      "Content: 1、保险费的支付 \n",
      "本附加合同的交费方式、交费期间和交费期数由您和我们约定并在保险单或批单、\n",
      "批注上载明。 \n",
      "您应当按照本附加合同约定向我们支付保险费。如果您选择分期支付保险费，您在\n",
      "支付首期保险费后，应在每期保险费约定支付日或之前支付对应各期的保险费。本附加\n",
      "合同仅支持按月分期支付保险费。 \n",
      "2、宽限期 \n",
      "分期支付保险费的，您支付首期保险费后，除本附加合同另有约定外，如果您到期\n",
      "未支付保险费，自保险费约定支付日的次日零时起 60 日为宽限期。宽限期内发生的保\n",
      "险事故，我们仍会承担保险责任，但在给付保险金时会扣减您欠交的保险费。 \n",
      "如果您在宽限期结束之后仍未支付保险费，则本附加合同自宽限期满的次日零时\n",
      "起效力中止。 \n",
      " \n",
      "您享有的权益 \n",
      "1、犹豫期 \n",
      "从您首次收到本附加合同之日起，有 15 日的犹豫期。在犹豫期内请您认真审视本\n",
      "附加合同，如果您认为本附加合同与您的需求不相符，您可以在此期间提出解除本附加\n",
      "合同，我们将无息退还您所支付的全部保险费。 \n",
      "解除本附加合同时，您需要提出申请，并提供您的保险合同及有效身份证件。自我\n",
      "们收到您的解除合同申请时起，本附加合同即被解除，合同解除前发生的保险事故我\n",
      "们不承担保险责任。 \n",
      "对于犹豫期内在线申请解除合同的，我们应在 1 个工作日内核定并通知申请人；如\n",
      "遇复杂情形，可将核定期限延展至 3 个工作日。 \n",
      " \n",
      "2、您解除合同的手续及风险\n",
      "\n",
      "Source: {'producer': 'Microsoft: Print To PDF', 'creator': 'PyPDF', 'creationdate': '2023-06-13T18:29:45+08:00', 'author': 'yemy', 'moddate': '2023-06-13T18:29:45+08:00', 'title': 'Microsoft Word - 13-2.ýND€™TQ˜1h\\x11Ý{\\x01tÑÝi§Áô\\x0ef.doc', 'source': '..\\\\langchain官网学习-v1版本\\\\data\\\\国华人寿保险股份有限国华附加互联网真爱全民保养老年金保险产品说明书.pdf', 'total_pages': 5, 'page': 4, 'page_label': '5'}\n",
      "Content: 主合同 \n",
      "保单年度末 保险费 累计保险费 保单价值 \n",
      "（退保金） 养老保险金 身故保险金 \n",
      "25 0 10000 13179 1004 13179 \n",
      "35 0 10000 9583 1004 10000 \n",
      "45 0 10000 0 1004 0 \n",
      "55 0 10000 0 1004 0 \n",
      "65 0 10000 0 1004 0 \n",
      " \n",
      "本公司重要声明： \n",
      "1、 上述利益演示中，身故保险金及保单价值（退保金）均为主合同保单年度末的数据演示，数据演示\n",
      "为给付养老保险金后的保险利益。 \n",
      "2、上述利益演示数据显示为四舍五入后的值，仅供参考。 \n",
      "3、本产品说明书所载资料供客户理解保险条款所用，各项内容均以保险条款为准。 \n",
      "投保人声明：本人已认真阅读并理解本产品说明书。 \n",
      " \n",
      "投保人签名：                         \n",
      "          年         月         日\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "让我继续查询更多关于用户权益的信息：\n",
      "Tool Calls:\n",
      "  retrieve_context (call_00_ODLORnCPnx5fc4WygPvy5sqm)\n",
      " Call ID: call_00_ODLORnCPnx5fc4WygPvy5sqm\n",
      "  Args:\n",
      "    query: 权益 权利 保障 保护 用户保障\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: retrieve_context\n",
      "\n",
      "Source: {'producer': 'Microsoft: Print To PDF', 'creator': 'PyPDF', 'creationdate': '2023-06-13T18:29:45+08:00', 'author': 'yemy', 'moddate': '2023-06-13T18:29:45+08:00', 'title': 'Microsoft Word - 13-2.ýND€™TQ˜1h\\x11Ý{\\x01tÑÝi§Áô\\x0ef.doc', 'source': '..\\\\langchain官网学习-v1版本\\\\data\\\\国华人寿保险股份有限国华附加互联网真爱全民保养老年金保险产品说明书.pdf', 'total_pages': 5, 'page': 0, 'page_label': '1'}\n",
      "Content: 国华附加互联网真爱全民保养老年金保险产品说明书 \n",
      " \n",
      "本产品说明书仅针对国华附加互联网真爱全民保养老年金保险。 \n",
      "在本产品说明书中， “您”指投保人， “我们” “本公司”均指国华人寿保险股份有\n",
      "限公司， “本附加合同”指您与我们之间订立的“国华附加互联网真爱全民保养老年金\n",
      "保险合同” 。 \n",
      " \n",
      "投保须知 \n",
      "投保条件： （1）投保人条件： \n",
      "凡年满 18 周岁，具有完全民事行为能力且对被保险人具有保险利益的人，\n",
      "均可作为本附加合同的投保人。 \n",
      "    （2）被保险人条件： \n",
      "被保险人就是受本附加合同保障的人，凡投保时身体健康，且符合我们承\n",
      "保条件的人，均可作为本附加合同的被保险人。 \n",
      "保险期间： 本附加合同的保险期间为终身， 自本附加合同生效日起至被保险人身故时止。  \n",
      "交费方式：趸交，期交：交至 35 周岁后的首个主合同的保单周年日、交至 40 周岁后的\n",
      "首个主合同的保单周年日、交至 45 周岁后的首个主合同的保单周年日、交至 50 周岁后\n",
      "的首个主合同的保单周年日、交至 55 周岁后的首个主合同的保单周年日、交至 60 周岁\n",
      "后的首个主合同的保单周年日。 \n",
      " \n",
      "保险责任 \n",
      "养老保险金领取起始日： \n",
      "若被保险人为男性，则本附加合同的养老保险金领取起始日为被保险人 60 周岁后\n",
      "的首个主合同的保单周年日；若被保险人为女性，则本附加合同的养老保险金领取起始\n",
      "日为被保险人 55 周岁后的首个主合同的保单周年日。\n",
      "\n",
      "Source: {'producer': 'Microsoft: Print To PDF', 'creator': 'PyPDF', 'creationdate': '2023-06-13T18:29:45+08:00', 'author': 'yemy', 'moddate': '2023-06-13T18:29:45+08:00', 'title': 'Microsoft Word - 13-2.ýND€™TQ˜1h\\x11Ý{\\x01tÑÝi§Áô\\x0ef.doc', 'source': '..\\\\langchain官网学习-v1版本\\\\data\\\\国华人寿保险股份有限国华附加互联网真爱全民保养老年金保险产品说明书.pdf', 'total_pages': 5, 'page': 4, 'page_label': '5'}\n",
      "Content: 主合同 \n",
      "保单年度末 保险费 累计保险费 保单价值 \n",
      "（退保金） 养老保险金 身故保险金 \n",
      "25 0 10000 13179 1004 13179 \n",
      "35 0 10000 9583 1004 10000 \n",
      "45 0 10000 0 1004 0 \n",
      "55 0 10000 0 1004 0 \n",
      "65 0 10000 0 1004 0 \n",
      " \n",
      "本公司重要声明： \n",
      "1、 上述利益演示中，身故保险金及保单价值（退保金）均为主合同保单年度末的数据演示，数据演示\n",
      "为给付养老保险金后的保险利益。 \n",
      "2、上述利益演示数据显示为四舍五入后的值，仅供参考。 \n",
      "3、本产品说明书所载资料供客户理解保险条款所用，各项内容均以保险条款为准。 \n",
      "投保人声明：本人已认真阅读并理解本产品说明书。 \n",
      " \n",
      "投保人签名：                         \n",
      "          年         月         日\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "基于检索到的信息，我为您总结用户享有的主要权益：\n",
      "\n",
      "## 用户享有的主要权益\n",
      "\n",
      "### 1. **犹豫期权益**\n",
      "- **15天犹豫期**：从首次收到保险合同之日起，有15日的犹豫期\n",
      "- **无理由退保**：在犹豫期内可以提出解除合同，保险公司将无息退还全部保险费\n",
      "- **快速处理**：在线申请解除合同的，1个工作日内核定（复杂情形可延至3个工作日）\n",
      "\n",
      "### 2. **宽限期权益**\n",
      "- **60天宽限期**：分期支付保险费的，到期未支付保险费有60日宽限期\n",
      "- **保障延续**：宽限期内发生的保险事故，保险公司仍承担保险责任\n",
      "- **费用扣减**：给付保险金时会扣减欠交的保险费\n",
      "\n",
      "### 3. **保险保障权益**\n",
      "- **养老保险金**：达到约定年龄后可领取养老保险金\n",
      "- **身故保险金**：提供身故保障\n",
      "- **保单价值**：具有退保金价值\n",
      "\n",
      "### 4. **知情权**\n",
      "- 有权获得完整的产品说明书\n",
      "- 有权了解保险条款和保障内容\n",
      "- 有权获得利益演示和相关信息\n",
      "\n",
      "### 5. **合同解除权**\n",
      "- 在符合条件的情况下可以解除保险合同\n",
      "- 需要提供保险合同及有效身份证件\n",
      "\n",
      "这些权益旨在保护用户的合法权益，确保用户在购买和使用保险产品过程中得到充分的保障和尊重。\n"
     ]
    }
   ],
   "source": [
    "query = \"用户享有什么权益?\"\n",
    "\n",
    "for event in agent.stream(\n",
    "    {\"messages\": [{\"role\": \"user\", \"content\": query}]},\n",
    "    stream_mode=\"values\",\n",
    "):\n",
    "    event[\"messages\"][-1].pretty_print()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchainV1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
